package com.ex2;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        // 创建一个 ServerSocket 对象，指定端口号
        ServerSocket serverSocket = new ServerSocket(8888);
        // 监听客户端的连接请求，如果有连接请求则接受并返回一个Socket对象
        Socket socket = serverSocket.accept();
        // 获取输入流，从客户端接收数据
        InputStream is = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int len = is.read(buffer);
        String data = new String(buffer, 0, len);
        System.out.println("server received: " + data);
        // 获取输出流，向客户端发送数据
        OutputStream os = socket.getOutputStream();
        os.write("hello, client".getBytes());
        // 关闭流和 Socket 连接
        os.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}
